<template>
    <picture>
        <slot name="meida">
            <!-- 例如：传入相关source，做媒体查询 -->
            <!-- <source srcset="/shared-assets/images/examples/surfer.jpg" media="(orientation: portrait)" /> -->
        </slot>
        <img ref="imageRef" v-bind="$attrs" :class="[ 'loading-img', $attrs.class ]" :src="props.src" :alt="props.alt" 
            @load="onSuccess" @error="onFail" :draggable="props.draggable"/>
    </picture>
</template>

<script lang="ts" setup>
import { ref } from '#imports';
 
type LazyImageProps = {
    loading?: 'eager'|'lazy',
    src: string,
    draggable?: boolean,
    alt?: string,
    loadingImage?: string,
    errorImage?: string,
}

defineOptions({
    inheritAttrs: false, // 禁止根节点的透传(防止class和style被透传到picture标签上)
});
const emits = defineEmits<{ load: [], fail: [] }>();
const props = withDefaults(defineProps<LazyImageProps>(),{
    loading: 'lazy',
    loadingImage: '/image/loading.svg',
    errorImage: '/image/neterror.svg',
    draggable: false,
});
const imageRef = ref<HTMLElement>();

const onSuccess = ()=>{
    imageRef.value?.classList.remove('loading-img');
    emits('load');
}
const onFail = ()=>{
    imageRef.value?.classList.remove('loading-img');
    imageRef.value?.classList.add('error-img');
    emits('fail');
}

</script>

<style lang="scss" scoped>
.loading-img{
    background-repeat: no-repeat;
    background-size: auto 10% !important;
    background-position: center;
    background-image: v-bind("'url(' + props.loadingImage + ')'");
}

.error-img{
    background-repeat: no-repeat;
    background-size: auto 60% !important;
    background-position: center;
    background-image: v-bind("'url(' + props.errorImage + ')'");
}
</style>